package com.lwbldy.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lwbldy.common.plugins.logging.annotation.Logging;
import com.lwbldy.common.plugins.logging.enums.BusinessType;
import com.lwbldy.common.plugins.repeat.annotation.RepeatSubmit;
import com.lwbldy.common.shiro.ShiroUtils;
import com.lwbldy.common.tools.*;
import com.lwbldy.modules.student.domain.*;
import com.lwbldy.modules.student.mapper.PreLogMapper;
import com.lwbldy.modules.student.mapper.SchoolDao;
import com.lwbldy.modules.student.service.*;
import com.lwbldy.modules.student.service.impl.PreRegistrationServiceImpl;
import com.lwbldy.modules.system.domain.SysUser;
import com.wf.captcha.utils.CaptchaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.Model;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 公共无需权限访问的控制器
 */
@Api(tags = "系统后台公共登录退出，获取验证码")
@Controller
public class SysCommonController {

    @Autowired
    IPreRegistrationService preRegistrationService;

    @Autowired
    LevelService levelService;

    @Autowired
    MajorService majorService;

    @Autowired
    SchoolService schoolService;
    @Autowired
    RegionService regionService;
    @Autowired
    HighSchoolService highSchoolService;
    @Autowired
    IPreLogService preLogService;
    @Autowired
    RefundService refundService;


    /**
     * 添加学生界面
     * @return
     */
    @RequestMapping({"","/","/index"})
    public String index(){
        return "student/preregistration/index";
//        return "system/login";
    }

    /**
     * 预报名学生
     * @param preRegistration
     * @return
     */
    @RequestMapping("preRegist")
    @ResponseBody
    public R preRegist(PreRegistration preRegistration, MultipartFile file,HttpServletRequest request){
        if(!CaptchaUtil.ver(ServletUtil.getRequest().getParameter("vercode"),ServletUtil.getRequest())){
            return R.error("验证码错误！");
        }

        String idCard = preRegistration.getIdCard();
        int sexInt = Integer.parseInt(idCard.substring(16,17));
        if(sexInt%2 == 0){
            preRegistration.setSex("女");
        }else {
            preRegistration.setSex("男");
        }
        // 验证层级
        String verStr = verifyMajor(preRegistration);
        if(verStr != null){
            return R.error(verStr);
        }

        preRegistration.setStatus(0);
        preRegistration.setCreateTime(new Date());
        try{
            String imgUrl = idCard+"."+FileUtils.getExtensionName(file.getOriginalFilename());
            preRegistration.setImageUrl(imgUrl);
            int r = preRegistrationService.insert(preRegistration);
            if(r == 1){
                String strDirPath = request.getSession().getServletContext().getRealPath("/upload");
                //保存图片到本地
                FileUtils.saveFile(file,strDirPath,idCard);
                return R.ok();
            }else {
                return R.error();
            }
        }catch (DuplicateKeyException exception){
            return R.error("身份证号已经提交，请勿重新提交。");
        }

    }

    private String verifyMajor(PreRegistration preRegistration){
        if(!(preRegistration.getSchoolId() == 1 || preRegistration.getSchoolId() == 2)){
            return "请选择正确的学校！";
        }

        boolean levelIsErr = true;
        int levelId = preRegistration.getLevelId();
        List<Level> levelList = levelService.queryBySchoolId(preRegistration.getSchoolId());
        for(Level level : levelList){
            if(level.getId() == levelId){
                // 找到了层级
                levelIsErr = false;
                break;
            }
        }

        if(levelIsErr){
            return "学校与专业不一致！";
        }

        List<Major> majorList = majorService.queryByLevelId(levelId);
        int majorId = preRegistration.getMajorId();
        boolean majorIsErr = true;
        for(Major major : majorList){
            if(major.getId() == majorId){
                // 找到了专业
                majorIsErr = false;
            }
        }

        if(majorIsErr){
            return "层级与专业不一致！";
        }

        return null;
    }


    @ApiOperation(value = "显示列表界面")
    @RequestMapping("/system/index")
    public String list(){
        return "/system/index";
    }


    @ApiOperation(value="用户登录界面")
    @GetMapping({"/system/login"})
    public String login(){
        return "system/login";
    }

    @ApiOperation(value="用户登录验证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名"),
            @ApiImplicitParam(name = "password", value = "密码"),
            @ApiImplicitParam(name = "vercode", value = "验证码"),
    })
    @PostMapping("/system/login")
    @ResponseBody
    @Logging(title = "用户登录",describe = "用户登录",type = BusinessType.QUERY)
    public R loginin(String username, String password, HttpSession session, String vercode) {
        try {
            if(!CaptchaUtil.ver(ServletUtil.getRequest().getParameter("vercode"),ServletUtil.getRequest())){
                return R.error("验证码错误！");
            }
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
            SysUser sysUserEntity = (SysUser) SecurityUtils.getSubject().getPrincipal();
            sysUserEntity.setSalt(null);
            sysUserEntity.setPassword(null);
            session.setAttribute("AdminSysUser",sysUserEntity);
            return R.ok("登录成功！").put("user", sysUserEntity);


        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return R.error("账号或密码不正确");
        } catch (LockedAccountException e) {
            return R.error("账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            return R.error("账户验证失败");
        }
    }


    /**
     * 验证码生成
     * @param request
     * @return captcha
     * */
    @ApiOperation(value="获取图片验证码")
    @RequestMapping("system/captcha/generate")
    public void generate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(request, response);
    }

    @RequestMapping("system/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "system/login";
    }

    @RepeatSubmit
    @RequestMapping("system/testRepaet")
    @ResponseBody
    public R testRepaet() {
        System.out.println("执行了测试是否重复");
        return R.ok();
    }


    @RequestMapping("common/querySchool")
    @ResponseBody
    public List<School> querySchool(){
        return schoolService.queryList(null);
    }

    @RequestMapping("common/queryLevelBySchoolId")
    @ResponseBody
    public List<Level> queryLevelBySchoolId(int schoolId){
        return levelService.queryBySchoolId(schoolId);
    }

    @RequestMapping("common/queryMajorByLevelId")
    @ResponseBody
    public List<Major> queryMajorByLevelId(int levelId){
        return majorService.queryByLevelId(levelId);
    }

    @RequestMapping("common/queryMajorBySchoolId")
    @ResponseBody
    public List<Major> queryMajorBySchoolId(int schoolId){
        return majorService.queryBySchoolId(schoolId);
    }


    @RequestMapping("common/queryRegionByPid")
    @ResponseBody
    public List<Region> queryRegionByPid(int pid){
        return regionService.queryByPid(pid);
    }

    @RequestMapping("common/queryPuilStatus")
    @ResponseBody
    public R queryPuilStatus(String idCard){
        List<PreLog> preLogList = preLogService.queryByIdCard(idCard);
        if(preLogList != null && preLogList.size() > 0){

            PreLog preLog = preLogList.get(0);
            if(preLog != null && preLog.getStatus() != null && preLog.getStatus() == 1){
                return R.ok("缴费成功。");
            }else{
                return R.ok("报名成功，请按照提示到支付宝、微信进行缴费。（如果已经缴费成功系统会延迟更新缴费成功信息）");
            }

        }else{
            List<PreRegistration> list = preRegistrationService.queryByIdcard(idCard);
            if(list != null && list.size() > 0){
                return R.error("提交报名成功，等待审核，请及时关注");
            }else{
                return R.error("没有找到该学生信息。");
            }
        }
    }

    @RequestMapping("common/buildStatusPage")
    public String buildStatusPage(String idCard, String bmxh, ModelMap map){
        if(idCard != null && idCard.trim().length() == 18 && bmxh != null){
            List<PreRegistration> preRegList = preRegistrationService.queryByIdcard(idCard);
            if(preRegList != null && preRegList.size() > 0){
                if(preRegList.get(0).getGraduateNo().equalsIgnoreCase(bmxh)){
                    List<PreLog> preLogList = preLogService.queryByIdCard(idCard);
                    map.put("preRegList",preRegList);
                    map.put("preLogList",preLogList);
                }
            }
        }
        return "student/preregistration/stuEditPage";
    }

    @RequestMapping("common/changeMajor")
    @ResponseBody
    public R changeMajor(PreRegistration registration){
        if(registration == null || registration.getSchoolId() == null
                || registration.getLevelId() == null || registration.getMajorId() == null || registration.getIdCard() == null
                || registration.getGraduateNo() == null){
            return R.error("参数不对。");
        }

        // 验证层级
        String verStr = verifyMajor(registration);
        if(verStr != null){
            return R.error(verStr);
        }

        int r = preRegistrationService.changeMajor(registration);
        if(r == 1){
            return R.ok("修改成功！");
        }else{
            return R.error("请核对身份证号或报名序号。");
        }
    }


    /**
     * 获取毕业学校
     * @param prefectureId
     * @return
     */
    @RequestMapping("common/queryBYSchool")
    @ResponseBody
    public List<HighSchool> queryBYSchool(int prefectureId){
        return highSchoolService.queryByPrefectureId(prefectureId);
    }

    /**
     * 跳转到退费界面
     * @return
     */
    @RequestMapping("common/refundPage")
    public String refundPage(String cardId,String graduateNo,ModelMap map){

        List<PreRegistration> registrationList = preRegistrationService.queryByIdcard(cardId);

        if(registrationList == null || registrationList.size() == 0){
            map.put("errmsg","没找到该学生。");
            return "student/preregistration/errorMsg";
        }
        PreRegistration preRegistration = registrationList.get(0);
        if(!preRegistration.getGraduateNo().equalsIgnoreCase(graduateNo)){
            map.put("errmsg","学号和准考证号不匹配。");
            return "student/preregistration/errorMsg";
        }

        if(preRegistration.getJfStatus() == null || preRegistration.getJfStatus() != 1){
            map.put("errmsg","还是未缴费状态不能申请退款。");
            return "student/preregistration/errorMsg";
        }

        map.put("preRegistration",preRegistration);
        map.put("preLog",preLogService.queryByIdCard(cardId).get(0));
        return "student/preregistration/refundPage";
    }

    @RequestMapping("common/refundStu")
    @ResponseBody
    public R refundStu(Refund refund,MultipartFile file,HttpServletRequest request){
        List<PreRegistration> registrationList = preRegistrationService.queryByIdcard(refund.getStuIdcard());

        if(registrationList == null || registrationList.size() == 0){
            return R.error("没找到该学生。");
        }
        PreRegistration preRegistration = registrationList.get(0);
        if(!preRegistration.getGraduateNo().equalsIgnoreCase(refund.getGraduateNo())){
            return R.error("学号和准考证号不匹配。");
        }

        if(preRegistration.getJfStatus() == null || preRegistration.getJfStatus() != 1){
            return R.error("还是未缴费状态不能申请退款。");
        }
        refund.setStatus(1);
        refund.setCreateTime(new Date());
        refund.setLastUpdate(new Date());
        String imgUrl = "tf/tf_"+refund.getStuIdcard()+"."+FileUtils.getExtensionName(file.getOriginalFilename());
        refund.setFpUrl(imgUrl);
        int r = refundService.save(refund);

        String strDirPath = request.getSession().getServletContext().getRealPath("/upload/tf");
        //保存图片到本地
        FileUtils.saveFile(file,strDirPath,"tf_"+refund.getStuIdcard());

        return R.resultRow(r);
    }

}
